# -*- coding: utf-8 -*-
import threading
from zc_core.client.mongo_client import Mongo
from zc_core.model.items import ItemData, Spu, ItemPoolData


class MaterialCodeHelper(object):
    _instance_lock = threading.Lock()
    _biz_inited = False

    def __new__(cls, *args, **kwargs):
        if not hasattr(MaterialCodeHelper, "_instance"):
            with MaterialCodeHelper._instance_lock:
                if not hasattr(MaterialCodeHelper, "_instance"):
                    MaterialCodeHelper._instance = object.__new__(cls)
        return MaterialCodeHelper._instance

    def __init__(self):
        if not self._biz_inited:
            self._biz_inited = True
            self.mongo = Mongo()
            coll = self.mongo.get_collection('item_data_pool')
            self.id_code_dict = dict()
            if coll:
                pool = coll.find()
                if pool:
                    for sku in pool:
                        self.id_code_dict[sku.get('_id')] = sku.get('materialCode')

    def fill(self, item):
        # 过滤条件
        if isinstance(item, ItemData) or isinstance(item, Spu) or isinstance(item, ItemPoolData):
            if item.get('skuId') and not item.get('materialCode'):
                mc = self.id_code_dict.get(item.get('skuId'))
                if mc:
                    item['materialCode'] = mc

        return item

    def get_by_sku(self, sku_id):
        if id:
            return self.id_code_dict.get(sku_id)

    # 关闭链接
    def close(self):
        self.mongo.close()
